from queue import RunQueue, NoJobsError
from job import SiftJob

import unittest

class RunQueueTestCase(unittest.TestCase):
    def setUp(self):
        self.queue = RunQueue()
        self.jobs = []
        self.jobs.append(SiftJob('google.com',80,'/',1))
        self.jobs.append(SiftJob('twitter.com',80,'/',1))
        self.jobs.append(SiftJob('facebook.com',80,'/',1))
        self.jobs.append(SiftJob('example.com',80,'/',1))
        self.jobs.append(SiftJob('facebook.com',80,'/',1))
        self.jobs.append(SiftJob('example.com',80,'/',1))
        
    def test_add_job(self):
        for job in self.jobs:
            self.queue.add_job(job)

    def test_queue_length(self):
        self.test_add_job()
        self.assertEqual(self.queue.length, len(self.jobs))

    def test_provide_job(self):
        self.test_add_job()
        provided_jobs = []
        for i in range(self.queue.length):
            try:
                provided_jobs.append(self.queue.provide_job())
            except NoJobsError:
                break

        # check added jobs are same as provided jobs, in correct order
        provided_jobs.reverse()
        self.assertEqual(self.jobs, provided_jobs)

    def test_optimize(self):
        self.test_add_job()
        self.queue.optimize()
        
        # jobs should now be grouped by host
        prev_host = None
        passed = []
        for i in range(self.queue.length):
            job = self.queue.provide_job()
            host = job.host
            if prev_host != host:
                assert host not in passed
                    
            passed.append(host)
            prev_host = host
            

if __name__ == '__main__':
    unittest.main()
